<?php
/*
 * Get a user's favorited recipes
 */
if(F3::exists("PARAMS['user']")):
	$id = F3::get("PARAMS['user']");
else:
	$id = false;
	return;
endif;

$param = array('1'=>$id);
$rids = DB::sql("SELECT rid from favorites where uid = ?",$param);
$recipes = array();
foreach($rids as $rid):
	$param = array('1'=>$rid['rid']);

	$re = DB::sql("SELECT avg(rating) as avg from ratings where rid = ?", $param);
	$tried = DB::sql("SELECT count(uid) as tried from ratings where rid = ?", $param);
	$directions = DB::sql("SELECT step, details from directions where rid = ?", $param);
	$result = DB::sql("SELECT * from recipes where rid = ?", $param);
	$tags = DB::sql("SELECT tid as tag_id, t.name from recipe_tags rt, tags t where rid = ? and rt.tid=t.id ", $param);
	$ingredients = DB::sql("SELECT quantity, m.name as measurement, m.abbrev, i.name as ingredient, optional, r.inid as ingredient_id, r.mid as measurement_id from recipe_ingredients r, ingredients i, measurements m where rid = ? and r.inid=i.id and r.mid=m.id", $param);	
	$response = array();
	
	foreach($result as $row){
		$response['rid'] = $rid['rid'];
		$response['name'] = $row['name'];
		$response['link'] = $row['link'];
		$response['photo'] = $row['photo'];
		$response['rating'] = $re[0]['avg'];
		$response['tried'] = $tried[0]['tried'];
		$author = $row['author'];
		$response['author'] = $row['author'];
		$response['Date'] = $row['Date'];
		$response['prep_time'] = $row['prep_time'];
		$response['inactive_time'] = $row['inactive_time'];
		$response['cook_time'] = $row['cook_time'];
		$response['privacy'] = $row['privacy'];
		$privacy = $row['privacy'];
		$response['yield'] = $row['yield'];
		$response['ingredients'] = $ingredients;
		$response['directions'] = $directions;
		$response['tags'] = $tags;
	}
	
	if($privacy==0):
		// public recipe
		$recipes[] = $response;
	elseif($id!=-1):
		$param = array('1'=>$author,'2'=>$id);
		$friend = DB::sql("SELECT id1 from friends where id1 = ? and id2 = ?", $param);
		if(($privacy==1 && $user_id!=$author)):
			// user is not authorized to view recipe
		elseif(($privacy==2 && count($friend)==0 && $id!=$author)):
			// user is not a friend
		else:
			// user is authorized
			$recipes[] = $response;
		endif;
	endif;
endforeach;


header('HTTP/1.1 200');
header("Content-Type: application/json");
echo json_encode($recipes);
?>